package com.test.reggieadmin.model.fragment.employee;

import android.app.Activity;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;

import com.lxj.xpopup.XPopup;
import com.test.reggieadmin.R;
import com.test.reggieadmin.base.BaseFragment;
import com.test.reggieadmin.base.BaseRVAdapter;
import com.test.reggieadmin.base.BaseRVHolder;
import com.test.reggieadmin.bean.BaseBean;
import com.test.reggieadmin.bean.EmployeeBean;
import com.test.reggieadmin.bean.GetDataType;
import com.test.reggieadmin.bean.PageBean;
import com.test.reggieadmin.bean.State;
import com.test.reggieadmin.databinding.FragmentEmployeeBinding;
import com.test.reggieadmin.http.API;
import com.test.reggieadmin.model.employee.AddEmployeeActivity;
import com.yechaoa.yutils.GsonUtil;
import com.yechaoa.yutils.ToastUtil;
import com.yechaoa.yutils.YUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 员工管理
 */
public class EmployeeFragment extends BaseFragment<FragmentEmployeeBinding, EmployeePrensenter> implements
        EmployeeView {

    private BaseRVAdapter<PageBean.DataBean> adapter;
    private int skip = 0;
    private int pageSize = 10;
    private EmployeeBean employeeBean;
    private int pos;
    private int status;
    private int ADD = 201;
    private int UPDATE = 202;
    private String id;

    @Override
    protected EmployeePrensenter createPresenter() {
        return new EmployeePrensenter(this);
    }

    @Override
    protected void initView() {
        employeeBean = GsonUtil.GsonToBean(String.valueOf(API.kv.decodeString(State.employee)), EmployeeBean.class);
    }

    @Override
    protected void initData() {
        viewBinding.fabAdd.setOnClickListener(v -> {//添加员工
            Intent intent = new Intent(getActivity(), AddEmployeeActivity.class);
            startActivityForResult(intent, ADD);
        });

        viewBinding.btnSearch.setOnClickListener(v -> {//搜索
            YUtils.showLoading("加载中...");
            skip = 1;
            presenter.page(skip, pageSize, viewBinding.etName.getText().toString().trim(),
                    GetDataType.REFRESH);
        });

        YUtils.showLoading("加载中...");
        presenter.page(skip, pageSize, viewBinding.etName.getText().toString().trim(),
                GetDataType.GETDATA);//查询

        adapter = new BaseRVAdapter<PageBean.DataBean>(R.layout.item_employee) {
            @Override
            public void onBindVH(BaseRVHolder holder, PageBean.DataBean data, int position) {
                Button btn_status = holder.getView(R.id.btn_status);
                LinearLayout ll_content = holder.getView(R.id.ll_content);

                holder.setText(R.id.tv_name, data.getName());
                holder.setText(R.id.tv_username, data.getUsername());
                holder.setText(R.id.tv_phone, data.getPhone());

                if (data.getStatus() == 1) {
                    holder.setText(R.id.tv_status, "正常");
                    btn_status.setText("禁用");
                } else {
                    holder.setText(R.id.tv_status, "已禁用");
                    btn_status.setText("启用");
                }

                //管理员可设置禁用、启用；非管理员不可设置禁用、启用
                if ("admin".equals(employeeBean.getData().getUsername())) {
                    btn_status.setVisibility(View.VISIBLE);
                } else {
                    btn_status.setVisibility(View.GONE);
                }

                btn_status.setOnClickListener(v -> {//禁用、启用
                    new XPopup.Builder(getActivity()).asConfirm("提示",
                            "确定" + (data.getStatus() == 1 ? "禁用" : "启用") + "该账号吗？",
                            () -> {
                                pos = position;
                                status = data.getStatus();

                                YUtils.showLoading("提交中...");
                                Map<String, Object> mapUpdate = new HashMap<>();
                                mapUpdate.put("updateUser", employeeBean.getData().getUsername());
                                mapUpdate.put("id", data.getId());
                                mapUpdate.put("status", (status == 1 ? 0 : 1));
                                presenter.update(mapUpdate);
                            })
                            .show();
                });

                ll_content.setOnClickListener(v -> {//编辑
                    pos = position;
                    id = data.getId();
                    Intent intent = new Intent(getActivity(), AddEmployeeActivity.class);
                    intent.putExtra("id", id);
                    startActivityForResult(intent, UPDATE);
                });
            }
        };

        empty("暂无数据");

        viewBinding.mRefreshLayout.setOnRefreshListener(refreshLayout -> {//下拉刷新
            skip = 0;
            presenter.page(skip, pageSize, viewBinding.etName.getText().toString().trim(),
                    GetDataType.REFRESH);
        });

        viewBinding.mRefreshLayout.setOnLoadMoreListener(refreshLayout -> {//上拉加载更多
            skip = adapter.getData().size();
            presenter.page(skip, pageSize, viewBinding.etName.getText().toString().trim(),
                    GetDataType.LOADMORE);
        });

        viewBinding.mRecyclerView.setAdapter(adapter);
        viewBinding.mRecyclerView.setLayoutManager(new GridLayoutManager(getActivity(), 1));//列数设置
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == ADD && resultCode == Activity.RESULT_OK) {
            skip = 0;
            presenter.page(skip, pageSize, viewBinding.etName.getText().toString().trim(),
                    GetDataType.REFRESH);
        } else if (requestCode == UPDATE && resultCode == Activity.RESULT_OK) {
            String name = data.getStringExtra("name");
            String username = data.getStringExtra("username");
            String phone = data.getStringExtra("phone");
            String sex = data.getStringExtra("sex");
            String idNumber = data.getStringExtra("idNumber");
            adapter.getData().get(pos).setName(name);
            adapter.getData().get(pos).setUsername(username);
            adapter.getData().get(pos).setPhone(phone);
            adapter.getData().get(pos).setSex(sex);
            adapter.getData().get(pos).setIdNumber(idNumber);
            adapter.notifyItemChanged(pos);
        }
    }

    @Override
    public void onError(String msg) {
        YUtils.hideLoading();
        ToastUtil.showCenter(msg);
    }

    @Override
    public void pageData(PageBean bean, int type) {
        YUtils.hideLoading();

        if (bean.getCode() == 200) {
            List<PageBean.DataBean> pageList = bean.getData();
            switch (type) {
                case GetDataType.GETDATA://获取数据成功
                    adapter.setNewData(pageList);
                    viewBinding.mRefreshLayout.setNoMoreData(false);
                    break;
                case GetDataType.REFRESH://刷新成功
                    adapter.setNewData(pageList);
                    viewBinding.mRefreshLayout.finishRefresh();
                    viewBinding.mRefreshLayout.setNoMoreData(false);
                    break;
                case GetDataType.LOADMORE://加载成功
                    if (pageList != null && !pageList.isEmpty()) {
                        adapter.addData(pageList);
                        if (pageList.size() < pageSize) {
                            viewBinding.mRefreshLayout.finishLoadMoreWithNoMoreData();
                        } else {
                            viewBinding.mRefreshLayout.finishLoadMore();
                        }
                    } else {
                        viewBinding.mRefreshLayout.finishLoadMoreWithNoMoreData();
                    }
                    break;
            }
        } else {
            ToastUtil.showCenter(bean.getMsg());
            viewBinding.mRefreshLayout.finishRefresh();
            viewBinding.mRefreshLayout.finishLoadMore();
        }
    }

    @Override
    public void pageError(String msg) {
        YUtils.hideLoading();
        viewBinding.mRefreshLayout.finishRefresh();
        viewBinding.mRefreshLayout.finishLoadMore();

        empty(msg);
    }

    @Override
    public void updateData(BaseBean bean) {
        YUtils.hideLoading();
        ToastUtil.showCenter(bean.getMsg());
        if (bean.getCode() == 200) {
            adapter.getData().get(pos).setStatus((status == 1 ? 0 : 1));
            adapter.notifyItemChanged(pos);
        }
    }

    private void empty(String msg) {
        View empty = LayoutInflater.from(getActivity()).inflate(R.layout.layout_no_data, null, false);
        TextView tv_tip = empty.findViewById(R.id.tv_tip);
        tv_tip.setText(msg);
        adapter.setEmptyView(empty);
    }
}